from django.test import LiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import unittest

from selenium.common.exceptions import WebDriverException

MAX_WAIT = 10


class AddNewFeedRSSTest(LiveServerTestCase):
    def setUp(self):
        self.browser = webdriver.Firefox()
        from django.contrib.auth.models import User
        user = User.objects.create_superuser('admin', 'exp@exp.com', 'adminpass')
        user.save()

    def tearDown(self):
        self.browser.quit()

    def wait_for_expected_window_title(self, title):
        start = time.time()
        while True:
            try:
                self.assertIn(title, self.browser.title)
                return
            except (AssertionError, WebDriverException):
                if time.time() - start > MAX_WAIT:
                    self.fail('Test URL Timeout')
                    # raise Exception

                time.sleep(0.5)

    def login_su(self):
        self.browser.get(self.live_server_url + '/login')
        self.assertIn('Login', self.browser.title)

        self.browser.find_element_by_name('username').send_keys('admin')
        self.browser.find_element_by_name('password').send_keys('adminpass')

        self.browser.find_element_by_id('btn-login').click()

        self.wait_for_expected_window_title('My Feeds')


    def test_login(self):
        # Test feed Before Login
        self.browser.get(self.live_server_url + '/feed/')
        self.wait_for_expected_window_title('Login')

        self.login_su()


    def test_add_new_rss_feed(self):
        self.login_su()
        # Test Add RSS FEED
        self.browser.get(self.live_server_url)

        self.browser.find_element_by_id('nav-link-my-feed').click()

        # self.assertIn('My Feeds', self.browser.title)
        self.wait_for_expected_window_title('My Feeds')


        # Test Add Recipe Feed
        rss_feed = {
            'title': "36Kr",
            'url': "http://36kr.com/feed/"
        }
        self.browser.find_element_by_id('feed-rss-title').send_keys(rss_feed['title'])
        self.browser.find_element_by_id('feed-rss-url').send_keys(rss_feed['url'])
        self.browser.find_element_by_id('feed-rss-add').click()

        # Refresh Page to verify addition
        self.browser.find_element_by_id('nav-link-my-feed').click()
        self.assertIn('My Feeds', self.browser.title)
        available_feeds = self.browser.find_element_by_id('available-feeds').text
        self.assertIn(rss_feed['title'], available_feeds)
        self.assertIn(rss_feed['url'], available_feeds)
